package com.zzzy.framework.common.dict;

import com.zzzy.common.util.AssertUtil;
import com.zzzy.framework.common.dict.dto.DictData;
import com.zzzy.framework.common.dict.dto.DictInfo;
import com.zzzy.framework.common.util.BeanUtils;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * Description: 字典数据
 *
 * @author fc
 * @date 2024/5/14
 */
@Service
public class DictService {

    /**
     * 字典数据缓存
     */
    private static final Map<String, DictInfo> DICT_DATA_MAP = new ConcurrentHashMap<>();


    @EventListener(ContextRefreshedEvent.class)
    public void initDictData(){
        List<DictInitInterface> dictInitServiceList = BeanUtils.getBeanListOfType(DictInitInterface.class);
        Map<String, DictInfo> finalMap = dictInitServiceList.stream().map(DictInitInterface::getDictInfoList)
                .flatMap(List::stream).collect(Collectors.toMap(DictInfo::getType, dictInfo -> dictInfo));

        DICT_DATA_MAP.putAll(finalMap);
    }
    public List<DictInfo> getDictInfoList() {
        return new ArrayList<>(DICT_DATA_MAP.values());
    }

    public List<DictData> getDictDataList(String dictType) {
        DictInfo dictInfo = DICT_DATA_MAP.get(dictType);
        AssertUtil.nonNull(dictInfo, "字典类型数据不存在");
        return dictInfo.getDictDataList();
    }

    public Map<Object, String> getDictDataMap(String dictType) {
        DictInfo dictInfo = DICT_DATA_MAP.get(dictType);
        AssertUtil.nonNull(dictInfo, "字典类型数据不存在");
        return dictInfo.getDictDataList().stream().collect(Collectors.toMap(DictData::getValue, DictData::getDescription));
    }

    public Map<Object, String> getDictDataMap(Class<? extends Enum> enumClass) {
        String enumClassName = enumClass.getSimpleName();
        enumClassName = enumClassName.substring(0, 1).toLowerCase() + enumClassName.substring(1);
        String dictType = enumClassName.replace("Enum", "");
        return getDictDataMap(dictType);
    }
}
